import AJAX from '@/utils/ajax'
import User from '@/components/user'
import { isLogin } from '@/utils'

class Love {
  constructor(obj) {
    if (isLogin()) {
      if (obj || cms.id) {
        this.show(obj || { id: cms.id })
      }
    }
    this.love = $('a.love')
    this.remind = $('a.remind')
    this.set(this.love, 'love')
    this.set(this.remind, 'remind')
    this.user = new User()
  }
  show(obj) {
    const { id, sid = 1 } = obj
    AJAX({ url: 'get', data: { id, sid, type: 'pc' } }).then(res => {
      this.isLove(res.gold || {})
    })
  }
  // 是否关注收藏
  isLove(data = {}) {
    if (data.loveid) {
      this.love.addClass('cur')
      this.love.html(this.love.html().replace('收藏', '已收藏'))
    }
    if (data.remindid) {
      this.remind.addClass('cur')
      this.remind.html(this.remind.html().replace('订阅', '已订阅'))
    }
  }
  set(elem, type) {
    const that = this
    elem.on('click', function() {
      if (isLogin()) {
        const id = $(this).data('id')
        const cid = $(this).data('cid')
        AJAX({ url: 'mark', data: { type, id, cid } }).then(res => {
          if (res.code > 0) {
            const name = type === 'love' ? '收藏' : '订阅'
            if ($(this).hasClass('cur')) {
              $(this).removeClass('cur')
              $(this).html(
                $(this)
                  .html()
                  .replace('已' + name, name)
              )
            } else {
              $(this).addClass('cur')
              $(this).html(
                $(this)
                  .html()
                  .replace(name, '已' + name)
              )
            }
          }
          layer.msg(res.msg)
        })
      } else {
        that.user.loginform()
      }
    })
  }
}

export default Love
